home
***
CD-ROM
|
disk
|
FTP
|
other
***
search
/
Apple Developer Connection Student Program
/
ADC Tools Sampler CD Disk 3 1999.iso
/
Documentation
/
Books
/
Learn Java on the Macintosh
/
Learn Java Projects
/
11.05 - simple draw
/
SimpleDraw.java
< prev
next >
Wrap
Text File
|
1996-04-22
|
3KB
|
104 lines
/* -------------------------------------------------------------
This applet paints a circle or square of the color you've chosen
wherever you click.
Java's classes: Applet (applet)
Event (awt) user-generated action
Graphics (awt) used for drawing
Color (awt) defines colors
Choice (awt) shape and color selection choices
Custom classes: SimpleDraw
Circle defines and draws circles
Square defines and draws squares
------------------------------------------------------------- */
import java.applet.Applet;
import java.awt.*;
public class SimpleDraw extends Applet {
Shape currentShape = null;
Choice shapeChoice;
Choice colorChoice;
/** Create the GUI. */
public void init() {
shapeChoice = new Choice();
shapeChoice.addItem("Circle");
shapeChoice.addItem("Square");
add(shapeChoice);
colorChoice = new Choice();
colorChoice.addItem("Red");
colorChoice.addItem("Green");
colorChoice.addItem("Blue");
add(colorChoice);
}
/** Draw the current shape. */
public void paint(Graphics g) {
if (currentShape != null)
currentShape.draw(g);
}
/** Create a new shape. */
public boolean mouseUp(Event e, int x, int y) {
Color color;
String shapeString = shapeChoice.getSelectedItem();
String colorString = colorChoice.getSelectedItem();
if (colorString.equals("Red"))
color = Color.red;
else if (colorString.equals("Green"))
color = Color.green;
else
color = Color.blue;
// Create a new shape of the appropriate type. Without inheritance,
// we have to write duplicate code for each of the shape types.
if (shapeString.equals("Circle"))
currentShape = new Circle();
else
currentShape = new Square();
currentShape.color = color;
currentShape.x = x;
currentShape.y = y;
repaint();
return true;
}
}
/** Shapes provide common characteristics for the circle and square. */
abstract class Shape {
static public final int shapeRadius = 20;
Color color;
int x;
int y;
abstract void draw(Graphics g);
}
/** Draws and maintains circle information. */
class Circle extends Shape {
void draw(Graphics g) {
g.setColor(this.color);
g.fillOval(this.x - shapeRadius, this.y - shapeRadius, shapeRadius * 2, shapeRadius * 2);
}
}
/** Draws and maintains square information. */
class Square extends Shape{
void draw(Graphics g) {
g.setColor(this.color);
g.fillRect(this.x - shapeRadius, this.y - shapeRadius, shapeRadius * 2, shapeRadius * 2);
}
}